var config = require('../../utils/config.js');
var util = require('../../utils/util.js');
var API_URL = config.API_URL;
var app = getApp();
var getCode_P = util.wxPromise(my.login);
var getUserInfo_P = util.wxPromise(my.getUserInfo);
var authorize_P = util.wxPromise(my.authorize);
var key;
/* 倒计时 */
function countdown(that, second) {
    var code = that.data.code;
    if (second < 0) {
        code.code = '重新获取';
        code.disabled = false;
        that.setData({
            code: code
        });
        return;
    }
    var time = setTimeout(function () {
        code.code = second--;
        that.setData({
            code: code
        });
        countdown(that, second);
    }, 1000)
}
/* 判断是否为空 */
function isEmpty(e, template) {
    var account = e.detail.value.account;
    var password = e.detail.value.password;
    var confirmPassword = e.detail.value.confirmPassword;
    var verifyCode = e.detail.value.verifyCode;
    if (account == "") {
        util.showNotice('请输入手机号');
        return true
    }
    if (password == "") {
        util.showNotice('请输入密码');
        return true
    }
    if (template == 'login') {
        return false
    }
    if (confirmPassword == "") {
        util.showNotice('请再次输入密码');
        return true
    }
    if (verifyCode == "") {
        util.showNotice('请输入验证码');
        return true
    }
    return false
}
/* 检查账号是否合法 */
function checkAccount(account) {
    var isMobile = util.checkMobilePhone(account);
    var isEmail = util.checkEmail(account);
    if (isMobile || isEmail) {
        return true;
    } else {
        return false;
    }
}
/* 检测两次输入的密码是否一样 */
function checkPassword(p1, p2) {
    if (p1 == p2) {
        return true
    } else {
        util.showNotice('两次输入的密码不一样');
        return false
    }
}
Page({
    data: {
        template: "login",
        item: {
            busy: false,
            account: "",
            password: "",
            confirmPassword: "",
            verifyCode: ""
        },
        code: {
            code: '获取验证码',
            disabled: true,
        },
        password: {
            showPW: 'password',
            showRE: 'password',
            focusPW: false,
            focusRE: false,
        },
        hiddenChoose: true
    },
    account: function (e) {
        var that = this;
        var code = this.data.code;
        console.log(code)
        console.log(e.detail.value)
        if (checkAccount(e.detail.value)) {
            code.disabled = false;
            that.setData({
                code: code,
                account: e.detail.value
            })
        } else {
            code.disabled = true;
            that.setData({
                code: code
            })
        }
    },
    // 忘记密码跳转
    goToForget: function (e) {
        var password = this.data.password;
        password.focusPW = false;
        password.focusRE = false;
        my.setNavigationBar({
            title: '重置密码',
        })
        this.setData({
            template: 'forget'
        })
    },
    /* 切换注册模板 */
    goToReg: function (e) {
        var password = this.data.password;
        password.focusPW = false;
        password.focusRE = false;
        my.setNavigationBar({
            title: '注册',
        })
        this.setData({
            template: 'register'
        })
    },
    // 切换登录页面
    goToLogin: function (e) {
        var password = this.data.password;
        password.focusPW = false;
        password.focusRE = false;
        my.setNavigationBar({
            title: '登录',
        })
        this.setData({
            template: 'login'
        })
    },
    // 返回主页
    goToIndex: function (e) {
        my.switchTab({
            url: '/pages/index/index',
        })
    },
    /* 改变密码显示与否 */
    changePassword: function () {
        var password = this.data.password;
        password.showPW = password.showPW == 'text' ? 'password' : 'text';
        password.focusPW = !password.focusPW;
        this.setData({
            password: password
        })
    },
    /* 登录 */
    login: function (e) {
        console.log(e);
        var that = this;
        var account = e.detail.value.account;
        var password = e.detail.value.password;
        // console.log(account)
        // console.log(password)
        var timestamp = Date.parse(new Date()) / 1000;
        var login_type;
        if (isEmpty(e, that.data.template)) {
            return
        }
        if (!checkAccount(account)) {
            util.showNotice('请输入正确的手机号或邮箱号')
            return
        }
        if (util.checkMobilePhone(account)) {
            login_type = 'mobile';
        } else {
            login_type = 'email';
        }
        my.httpRequest({
            url: API_URL.login,
            data: {
                from: 'mina',
                account: account,
                password: password,
                login_type: login_type,
                identifier: '',
                push_token: '',
                timestamp: timestamp
            },
            method: 'POST',
            success: function (res) {
                console.log(res);
                if (res.data.status == 200) {
                    app.globalData.usersInfo = res.data.usersInfo;
                    console.log(res.data.usersInfo)
                    var user = res.data.usersInfo;
                    if (user.length == 1) {
                        my.getAuthCode({
                            scopes: 'auth_user', // 主动授权：auth_user，静默授权：auth_base
                            success: (res) => {
                                console.log(res)
                                if (res.authCode) {
                                    // 认证成功
                                    // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
                                    my.httpRequest({
                                        url: API_URL.login, // 该url是自己的服务地址，实现的功能是服务端拿到authcode去开放平台进行token验证
                                        data: {
                                            authcode: res.authcode
                                        },
                                        success: (res) => {
                                            // 授权成功并且服务器端登录成功

                                            app.globalData.userInfo = user;
                                        },
                                        fail: () => {
                                            // 根据自己的业务场景来进行错误处理
                                        },
                                    });
                                    // 获取用户信息
                                    my.getAuthUserInfo({
                                        success: (res) => {
                                            // my.alert(res.nickName); //获取的用户昵称
                                            // my.alert(res.avatar); //获取的用户头像图片
                                            console.log(res)
                                            app.globalData.avatr = res.avatar;
                                            app.globalData.userName = res.nickName;
                                            
                                        }
                                    });
                                }
                            },
                        });
                        // getCode_P()
                        //     .then(res => {
                        //         return util.POST(API_URL.get_openid, { loginCode: res.code })
                        //     }).then(res => {
                        //         console.log(res);
                        //         my.setStorage({
                        //             key: 'openId',
                        //             data: res.data.appid,
                        //         })
                        //         my.setStorage({
                        //             key: 'unionId',
                        //             data: res.data.appid,
                        //         })
                        //     }).catch(res => {
                        //         console.log(res)
                        //     })

                        my.setStorage({
                            key: 'loginToken',
                            data: user[0].token,
                        })
                        my.setStorage({
                            key: 'user',
                            data: res.data.usersInfo[0],
                        })
                        my.setStorage({
                            key: 'hasIdentified',
                            data: res.data.usersInfo[0].identity_status == 0 ? false : true,
                        })
                        my.setStorage({
                            key: 'hasBindLive',
                            data: res.data.usersInfo[0].live_type == "" ? false : true,
                        })
                        my.setStorage({
                            key: 'isTGX',
                            data: res.data.usersInfo[0].is_yudutianguangxu == 0 ? false : true,
                        })
                        my.setStorage({
                            key: 'hasStore',
                            data: res.data.usersInfo[0].isExistStore == 0 ? false : true,
                        })
                        app.globalData.refresh = true;
                        app.globalData.userInfo = user;
                        app.globalData.logout = false;
                        console.log(app.globalData.routeF)
                        // if (app.globalData.routeF == 'switchTab') {
                        //     my.switchTab({
                        //         url: app.globalData.route,
                        //     })
                        // } else {
                        //     my.switchTab({
                        //         url: app.globalData.route,
                        //     })
                        // }
                        my.navigateBack({
                            delta: 5
                        })
                    } else {
                        var account = that.data.account;
                        account = account.split('');
                        account.splice(3, 5, "*****");
                        account = account.join('');
                        var userData = res.data.usersInfo;
                        userData = userData.map(item => {
                            switch (item.regSrc) {
                                case "1": item.img = '/images/login/ygbh.png'; break;
                                case "2": item.img = '/images/login/zxyl.png'; break;
                                case "3": item.img = '/images/login/logo.png'; break;
                            }
                            return item;
                        })
                        that.setData({
                            hiddenChoose: false,
                            userData: userData,
                            account: account
                        })
                    }
                } else {
                    util.showNotice(res.data.msg);
                }
            },
            fail: function (res) { },
            complete: function (res) { },
        })
    },
})